document.querySelector(".home-btn").addEventListener("click", () => {
  window.location.href = "/";
});

// 全局变量
let socket;
let wvpRunning = false;
let autoScroll = true;
let stats = {
  totalLoops: 0,
  successCount: 0,
  failureCount: 0,
};

// 高度匹配函数
function matchRightCardHeight() {
  const left = document.getElementById("leftCard");
  const right = document.getElementById("rightCard");
  if (left && right) {
    const leftHeight = left.offsetHeight;
    right.style.height = leftHeight + "px";
  }
}

// 初始化Socket.io连接
function initSocket() {
  socket = io();

  socket.on("connect", function () {
    console.log("Socket connected");
    addLogEntry("js: 已连接到服务器");
  });

  socket.on("disconnect", function () {
    console.log("Socket disconnected");
  });

  socket.on("wvp_log", function (data) {
    if (data.message) addLogEntry(data.message);
  });

  socket.on("wvp_status", function (data) {
    updateWvpStatus(data.running);
    if (data.stats) {
      stats = data.stats;
      updateStats();
    }
  });
}

// 更新WVP状态
function updateWvpStatus(isRunning) {
  const statusElem = document.getElementById("wvpStatus");
  const btn = document.getElementById("startBtn");

  if (isRunning) {
    statusElem.innerHTML =
      '<span class="status-indicator status-active"></span><span>运行中</span>';
    btn.innerHTML = '<i class="bi bi-stop-circle me-2"></i>停止测试';
    btn.classList.replace("btn-success", "btn-danger");
    wvpRunning = true;
  } else {
    statusElem.innerHTML =
      '<span class="status-indicator status-inactive"></span><span>未运行</span>';
    btn.innerHTML = '<i class="bi bi-play-circle me-2"></i>开始测试';
    btn.classList.replace("btn-danger", "btn-success");
    wvpRunning = false;
  }
}

// 添加日志条目
function addLogEntry(message) {
  const now = new Date();
  const timestamp = now.toTimeString().split(" ")[0]; // HH:MM:SS 格式
  const logContainer = document.getElementById("logContainer");
  const logEntry = document.createElement("div");
  logEntry.className = "log-entry";

  const timeSpan = document.createElement("span");
  timeSpan.className = "log-timestamp";
  timeSpan.textContent = `[${timestamp}] `;
  timeSpan.style.color = "#5bc0de";

  const messageSpan = document.createElement("span");
  messageSpan.className = "log-message";
  messageSpan.textContent = message;

  logEntry.appendChild(timeSpan);
  logEntry.appendChild(messageSpan);
  logContainer.appendChild(logEntry);

  if (autoScroll) {
    logContainer.scrollTop = logContainer.scrollHeight;
  }

  matchRightCardHeight();
}

// 更新统计信息
function updateStats() {
  document.getElementById("totalLoops").textContent = stats.totalLoops;
  document.getElementById("successCount").textContent = stats.successCount;
  document.getElementById("failureCount").textContent = stats.failureCount;

  const total = stats.successCount + stats.failureCount;
  const successRate =
    total > 0 ? Math.round((stats.successCount / total) * 100) : 0;

  document.getElementById("successRateBar").style.width = `${successRate}%`;
  document.getElementById(
    "successRateText"
  ).textContent = `成功率: ${successRate}%`;
}

// 启动/停止测试
function toggleWvpTest() {
  if (wvpRunning) {
    stopWvpTest();
  } else {
    startWvpTest();
  }
}

// 启动测试
async function startWvpTest() {
  const domain = document.getElementById("domain").value;
  const username = document.getElementById("username").value;
  const rawPassword = document.getElementById("password").value;
  const deviceIds = document.getElementById("deviceIds").value;
  const maxLoops = document.getElementById("maxLoops").value;
  const mediaCheckUrl = document.getElementById("mediaCheckUrl").value;
  const checkInterval = document.getElementById("checkInterval").value;

  if (!domain || !username || !rawPassword) {
    addLogEntry("js: 错误：请填写域名、用户名和密码");
    return;
  }

  try {
    addLogEntry("js: 正在获取Access Token...");

    const password = md5(rawPassword).toLowerCase();
    const tokenResponse = await fetch(
      `/get_wvp_token?domain=${encodeURIComponent(
        domain
      )}&username=${encodeURIComponent(username)}&password=${password}`
    );
    const tokenData = await tokenResponse.json();

    if (tokenData.status !== "success" || !tokenData.access_token) {
      throw new Error(tokenData.message || "获取Access Token失败");
    }

    const accessToken = tokenData.access_token;
    addLogEntry("js: 成功获取Access Token");

    const formData = {
      device_ids: deviceIds
        .split(/[\n,]+/)
        .map((id) => id.trim())
        .filter((id) => id),
      max_loops: parseInt(maxLoops) || 100,
      access_token: accessToken,
      media_check_url: mediaCheckUrl,
      check_interval: parseInt(checkInterval) || 5,
      domain: domain,
    };

    const testResponse = await fetch("/start_wvp_test", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(formData),
    });

    const testData = await testResponse.json();
    if (testData.status === "success") {
      updateWvpStatus(true);
    } else {
      addLogEntry(`js: 启动失败: ${testData.message}`);
    }
  } catch (error) {
    addLogEntry(`js: 启动失败: ${error.message}`);
  }
}

// 停止测试
function stopWvpTest() {
  fetch("/stop_wvp_test", {
    method: "POST",
  })
    .then((response) => response.json())
    .then((data) => {
      if (data.status === "success") {
        updateWvpStatus(false);
      }
    });
}

// 初始化事件监听器
function initEventListeners() {
  document.getElementById("startBtn").addEventListener("click", toggleWvpTest);

  document.getElementById("clearLogBtn").addEventListener("click", () => {
    document.getElementById("logContainer").innerHTML = "";
    addLogEntry("js: 日志已清空");
  });

  // 向下按钮滚动
  const logContainer = document.getElementById("logContainer");
  const scrollBtn = document.getElementById("scrollToBottomBtn");

  logContainer.addEventListener("scroll", () => {
    const atBottom =
      logContainer.scrollHeight - logContainer.scrollTop <=
      logContainer.clientHeight + 5;
    autoScroll = atBottom;

    if (scrollBtn) {
      if (autoScroll) {
        scrollBtn.classList.add("active");
        scrollBtn.classList.remove("inactive");
      } else {
        scrollBtn.classList.add("inactive");
        scrollBtn.classList.remove("active");
      }
    }
  });

  if (scrollBtn) {
    scrollBtn.addEventListener("click", () => {
      logContainer.scrollTop = logContainer.scrollHeight;
      autoScroll = true;
      scrollBtn.classList.add("active");
      scrollBtn.classList.remove("inactive");
    });
  }

  // 密码显示切换
  const togglePassword = document.getElementById("togglePassword");
  const passwordInput = document.getElementById("password");

  if (togglePassword && passwordInput) {
    togglePassword.addEventListener("click", () => {
      const type =
        passwordInput.getAttribute("type") === "password" ? "text" : "password";
      passwordInput.setAttribute("type", type);

      togglePassword.classList.toggle("bi-eye");
      togglePassword.classList.toggle("bi-eye-slash");
    });
  }
}

// 页面加载完成后初始化
document.addEventListener("DOMContentLoaded", () => {
  initSocket();
  initEventListeners();
  addLogEntry("js: WVP启停流控制工具已启动");
  addLogEntry("js: 请配置设备ID和访问令牌");

  matchRightCardHeight();
  setTimeout(matchRightCardHeight, 100);
  window.addEventListener("resize", matchRightCardHeight);

  fetch("/get_wvp_status")
    .then((response) => response.json())
    .then((data) => {
      if (data.status === "success") {
        updateWvpStatus(data.running);
        if (data.stats) {
          stats = data.stats;
          updateStats();
        }
      }
    });
});
